from django.http import HttpResponse
from django.shortcuts import render,redirect
from django.contrib.auth import authenticate,login,logout
from .models import login_registration
# Create your views here.


def regist(requests):
    if requests.method == 'GET':
        # 清空数据库
        # login_registration.objects.all().delete()
        return render(requests, 'regist.html')
    # 注册
    error_msg = ""
    if requests.method == "POST":
        password = requests.POST.get("password", None)
        pwd2 = requests.POST.get("password2", None)
        username = requests.POST.get('username', None)
        phone = requests.POST.get('phone', None)
        # 将数据上传数据库


        if phone == '' or username=='' or password=='' or pwd2=='':
            error_msg = "请填写完整信息!"
            return render(requests, 'regist.html', {"error": error_msg})

        else:
            if password == pwd2:

                datas = login_registration.objects.filter(username=username)
                # 判断用户名是否存在
                if datas.exists():
                    error_msg = "用户存在！！"
                else:
                    error_msg = "注册成功！"
                    login_registration.objects.create(username=username, password=password, phone=phone)
            else:
                error_msg = "两次密码不一致！! "

        return render(requests,'regist.html',{"error":error_msg})

def login(requests):
    error_msg = ''
    if requests.method == 'GET':
        return render(requests, 'login.html')
    if requests.method == 'POST':
        password = requests.POST.get("password", None)
        username = requests.POST.get("username",None)
        # 输出页面输入的 账号密码
        print("网页输入的账户为%s，密码为%s"%(username,password))
        # 读取并搜索 数据库记得账户和密码
        datas = login_registration.objects.filter(username=username)
        # 判断账号是否已存在
        if datas.exists():
            # print("账号存在")
            for data in datas:
                # 判断密码是否与 数据库中的相同
                if password == data.password:
                    error_msg = "登录成功！"
                    # 输出数据库中的  账号密码
                    print("数据库中的账户为%s，密码为%s"%(data.username, data.password))
                    return render(requests, 'index.html')
                else:
                    error_msg = "密码错误！"
        else:
            error_msg = "账号有误或不存在！！"
        return render(requests, 'login.html', {"error": error_msg})


def index_html(requests):
    if requests.method == 'POST':
        # response = HttpResponse()
        # responses = HttpResponseRedirect('/uauth/login/')
        # responses.delete_cookie('ticket')
        # return responses
        return render(requests,"index.html")
    else:
        return render(requests,"index.html")


def logout(requests):
    return render(requests, "login.html")